<?php


if( !empty( $_GET['map'] ) && $map = $db->id_get( 'map', $_GET['map'] )) {
	$x = intval( $_GET['x'] );
	$y = intval( $_GET['y'] ) ;
	$link = SELF."&x=$x&y=$y&map={$map['id']}&nomenu";
} else {
	$link = SELF."&id=".intval( $_GET['eventedit'] );
}

$rc = new data_controller( 'event', $link );
$rc->add( 'name', 'Name' );
$rc->add( 'template', 'Template', 0, 1, 1, 0, 'checkbox' );
$rc->prefix = 'event';

if( $map ) {
	$rc->auto['create'] = array( 'map' => $map['id'], 'x' => $x, 'y' => $y );
} else {
	$rc->add( 'map', 'Karte', 1, 1, 1, 1, 'select', $db->select( 'map' )->relate());
	$rc->add( 'x', 'X-Position' );
	$rc->add( 'y', 'Y-Position' );
}


$rc->run();

if( $map ) {
	$event = $db->get( 'event', "x = $x AND y = $y AND map = {$map['id']}", 1 );
} else {
	if( !empty( $_GET['eventedit'] ))
		$event = $db->id_get( 'event', $_GET['eventedit'] );
}

if( $event ) {
	if( isset( $_GET['eventcreate']) && !empty( $_POST['copy'] )) {
		foreach( $db->get( 'event_page', 'event='.intval( $_POST['copy'] )) as $page ) {
			$page['event'] = $event['id'];
			$page['id'] = NULL;
			$db->insert( 'event_page', $page );
		}
	}

	$sprites = glob( "{img/objects/*,img/charset/*}", GLOB_BRACE );
	$sprites = array_combine( $sprites, $sprites );
	$sprites[''] = 'Keine Grafik';
	$levels = array( "Below Hero", "Same Level as Hero", "Above Hero", "Rooftile" );
	$triggers = array( "None", "Touch", "Key", "Autostart" );
	$moves = array( "Keine Bewegung", "Random" );

	$rcp = new data_controller( 'event_page', $link );
	$rcp->add( 'id', 'Id', 1, 0, 0 );
	$rcp->add( 'sprite', 'Grafik', 1, 1, 1, 0, 'select', $sprites );
	$rcp->add( 'trigger', 'Auslöser', 1, 1, 1, 0, 'select', $triggers );
	$rcp->add( 'level', 'Kollision', 1, 1, 1, 0, 'select', $levels );
	$rcp->add( 'movement', 'Bewegung', 1, 1, 1, 0, 'select', $moves );
	$rcp->add( 'script', 'Script', 0, 1, 1, 0, 'textarea' );

	$rcp->auto['create'] = array( 'event' => $event['id'] );
	$rcp->condition = "event = {$event['id']}";
	$rcp->prefix = 'page';
	$rcp->run();

	echo '<div class="well"><h1>Event bearbeiten</h1>'.$rc->get_edit( $event['id'] ).'</div>';
	echo '<div class="well"><h1>Event Scripte</h1>'.$rcp->get_form()->append( $rcp->get_list()).'</div>';
	echo '<div class="well"><h1>Event Löschen</h1><p><a href="'.$link.'&eventdelete='.$event['id'].'">Event Löschen</a></p></div>';
} else {
	$templates = $db->select( 'event', 'template' )->relate();
	$templates[0] = 'Keine Vorlage';

	$form = $rc->get_create();
	$form->select( 'copy', 'Kopieren von', $templates );

	if( $map ) {
		echo '<div class="well"><h1>Event erstellen</h1>'.$form.'</div>';
	} else {
		echo '<table width="100%"><tr><td width="450"><div class="well"><h1>Event erstellen</h1>'.$form.'</div></td>';
		echo '<td><div class="well"><h1>Eventliste</h1>'.$rc->get_list().'</div></td></tr></table>';
	}
}